﻿(function () {

    layui.use(["layer", "jquery", "table", "form", "tree"], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
        var tree = layui.tree;

        $(document).ready(function () {
            $("#btnSearch").click(onBtnSearchClick);
        });

        table.render({
            elem: "#User",
            url: "/User/List",
            height: "full-68", // (10 + 38 + 10 + 10)
            page: false,
            method: "POST",
            where: getTableQueryParam(),
            even: true,
            totalRow: true,
            parseData: function (res) {
                //console.log(res);
                return {
                    "code": res.Success == true ? 0 : -1,
                    "msg": res.Msg,
                    "count": res.Count,
                    "data": res.Data,
                    "totalRow": {
                        count: res.Total
                    }
                };
            },
            cols: [[
                { type: 'numbers', title: 'No.', width: 60, fixed: 'center', totalRow: '{{= d.TOTAL_ROW.count }}' }
                , { field: "Phone", width: 120, align: "center", title: "手机号码" }
                , { field: "Name", width: 100, align: "center", title: "姓名" }
                , { field: "InvitationCode", width: 100, align: "center", title: "邀请码" }
                , { field: "ReferenceName", width: 100, align: "center", title: "推荐人" }
                , { field: "ReferenceInvitationCode", width: 120, align: "center", title: "推荐人邀请码" }
                , { field: "CreateTime", width: 180, align: "center", title: "创建时间" }
                , {
                    field: "State", width: 60, align: "center", title: "状态", templet: function (d) {
                        if (d["State"] == 1) { return "启用"; }
                        else {
                            return '<span style="color: red;">禁用</span>';
                        }
                    }
                }
                , { align: "center", title: "操作", fixed: "right", minWidth: 560, toolbar: "#tableToolBar" }
            ]]
        });

        table.on("tool(user)", function (obj) {
            var layEvent = obj.event;

            if (layEvent == "tool-viewUserAccountInfo") {
                onViewUserAccountInfoHandler(obj);
            }
            else if (layEvent == "tool-viewUserStructure") {
                onViewUserStructureHandler(obj);
            }
            else if (layEvent == "tool-updateUser") {
                onUpdateUserHandler(obj);
            }
            else if (layEvent == "tool-updateUserReference") {
                onUpdateUserReferenceHandler(obj);
            }
            else if (layEvent == "tool-updateUserState") {
                onUpdateUserStateHandler(obj);
            }
            else if (layEvent == "tool-viewShopManagerLevel") {
                onViewShopManagerLevelHandler(obj);
            }
            else if (layEvent == "tool-resetPwd") {
                onResetPwdHandler(obj);
            }
        });

        form.render("select", "filter-Search-State");

        function getTableQueryParam() {
            return {
                Phone: $("#txtSearchPhone").val(),
                Name: $("#txtSearchName").val(),
                InvitationCode: $("#txtSearchInvitationCode").val(),
                Reference: $("#txtSearchReference").val(),
                ReferenceInvitationCode: $("#txtSearchReferenceInvitationCode").val(),
                State: $("#sel-Search-State").val()
            };
        }

        function onBtnSearchClick() {
            table.reloadData("User", {
                where: getTableQueryParam()
            });
        }

        function reloadTable() {
            $("#btnSearch").trigger("click");
        }

        function onViewUserAccountInfoHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var userId = data.Id;

            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/UserAccountInfo/QueryByUserId", {
                method: "POST",
                data: "userId=" + userId,
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        handleData(data.Data);
                    } else {
                        layer.msg(addStyle("加载数据失败: " + data.Msg),
                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                        );
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data2) {
                layer.open({
                    type: 1,
                    title: "满堂创品",
                    shade: [0.1, '#000'],
                    skin: 'layui-layer-molv',
                    area: ["350px", "100%"],
                    resize: false,
                    content: '<div id="ViewUserAccountInfoDlg2">' + $("#ViewUserAccountInfoDlg").html() + '</div>'
                });

                var width = $("#ViewUserAccountInfoDlg2").parent().width();
                var height = $("#ViewUserAccountInfoDlg2").parent().height();
                var height2 = height - 41 - 10 - 10;
                var host = tool.getMTCPPhoneClientWebAddress();
                if (data2.WechatImagePath) {
                    var wechatSrc = host + data2.WechatImagePath;
                    $("#ViewUserAccountInfoDlg2 .wechat")
                        .css("width", width + "px")
                        .css("height", height2 + "px")
                        .attr("src", wechatSrc);
                }
                if (data2.AlipayImagePath) {
                    var alipaySrc = host + data2.AlipayImagePath;
                    $("#ViewUserAccountInfoDlg2 .alipay")
                        .css("width", width + "px")
                        .css("height", height2 + "px")
                        .attr("src", alipaySrc);
                }
                if (data2.BankAccountName) {
                    $("#ViewUserAccountInfoDlg2 .lbBankAccountName").text(data2.BankAccountName);
                }
                if (data2.Bank) {
                    $("#ViewUserAccountInfoDlg2 .lbBankName").text(data2.Bank);
                }
                if (data2.BankCardNo) {
                    $("#ViewUserAccountInfoDlg2 .lbBankCardNo").text(data2.BankCardNo);
                }
            }
        }

        function onViewUserStructureHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var userId = data.Id;
            showUserStructureDlg(userId);
        }

        function showUserStructureDlg(userId) {
            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                area: ["350px", "80%"],
                offset: "10%",
                resize: false,
                content: '<div Id="ViewUserStructureDlg2">' + $("#ViewUserStructureDlg").html() + '</div>'
            });

            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/User/QueryUserStructure", {
                method: "POST",
                data: "UserId=" + userId,
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        handleData(data.Data);
                    } else {
                        layer.msg(addStyle("加载数据失败: " + data.Msg),
                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                        );
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data) {
                var treeData = Convert_2_TreeData(data, userId);
                var n = treeData.length;
                var dom = $("#ViewUserStructureDlg2 div").eq(0);
                tree.render({
                    elem: dom,
                    id: "Tree",
                    data: treeData
                });
            }
        }

        function Convert_2_TreeData(arr, rootUserId) {
            var arr2 = arr.filter(item => item["Id"] == rootUserId);
            if (arr2.length > 0) {
                var arr3 = [];
                arr.forEach((item, i) => {
                    var arr4 = arr.filter(item2 => item["InvitationCode"] == item2["ReferenceInvitationCode"]);
                    item["children"] = arr4;
                    arr3.push(item);
                });

                var root = arr2[0];
                var treeArr = [];
                var treeObj = Convert_2_TreeItemData(root);
                treeArr.push(treeObj);
                fun1(treeObj["obj"]["InvitationCode"], treeObj["children"]);
                return treeArr;
                function fun1(invitationCode, parent) {
                    var arr4 = arr3.filter(x => x["ReferenceInvitationCode"] == invitationCode);
                    if (arr4.length > 0) {
                        for (var i = 0; i < arr4.length; i++) {
                            var item2 = arr4[i];
                            var treeObj2 = Convert_2_TreeItemData(item2);
                            parent.push(treeObj2);
                            fun1(item2["InvitationCode"], treeObj2["children"]);
                        }
                    }
                }

                function Convert_2_TreeItemData(obj) {
                    return {
                        id: obj["Id"],
                        title: obj["Name"] + " - " + obj["Phone"],
                        obj: obj,
                        children: []
                    };
                }
            }
            return [];
        }

        function onUpdateUserHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var _userId = data.Id;

            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                resize: false,
                content: '<div Id="UpdateUserInfoDlg2">' + $("#UpdateUserInfoDlg").html() + '</div>'
            });

            $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-phone]").val(data["Phone"]);
            $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-name]").val(data["Name"]);

            form.verify({
                name: [/[\u4e00-\u9fa5a-zA-Z0-9]{2,10}/, "姓名格式不正确！"]
            });

            form.on("submit(filter-updateUserDlg-ok)", function (data) {
                //console.log(data);

                layer.confirm("确定要修改数据吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            UserId: _userId,
                            Phone: $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-phone]").val(),
                            Name: $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-name]").val()
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/User/UpdateUser", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(_layerId);
                                    layer.msg(addStyle("修改数据成功！"), {
                                        icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                            reloadTable();
                                        }
                                    });
                                } else {
                                    layer.msg(addStyle("修改数据失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                    );
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );

                return false;
            });
        }

        function onUpdateUserReferenceHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var userId = data.Id;
            var name = data["Name"];
            var invitationCode = data["InvitationCode"];
            var reference = data["ReferenceName"];
            var referenceInvitationCode = data["ReferenceInvitationCode"];

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                resize: false,
                content: '<div Id="UpdateUserReferenceDlg2">' + $("#UpdateUserReferenceDlg").html() + '</div>'
            });

            $("#lb-UpdateUserReferenceDlg-Name").text(name);
            $("#lb-UpdateUserReferenceDlg-InvitationCode").text(invitationCode);
            $("#lb-UpdateUserReferenceDlg-Reference").text(reference);
            $("#txt-UpdateUserReferenceDlg-ReferenceInvitationCode").val(referenceInvitationCode);

            $("#btn-UpdateUserReferenceDlg-Search").click(onUpdateUserReferenceDlgSearchBtnClick);
            $("#btn-UpdateUserReferenceDlg-OK").click(onUpdateUserReferenceDlgOKBtnClick);
            $("#txt-UpdateUserReferenceDlg-ReferenceInvitationCode").bind("input propertychange", onReferneceInputChange);

            function onReferneceInputChange() {
                isVerified = false;
            }

            function onUpdateUserReferenceDlgSearchBtnClick() {
                var tableData = table.getData("User");
                var code = $("#txt-UpdateUserReferenceDlg-ReferenceInvitationCode").val();
                var itemData = null;
                for (var i = 0; i < tableData.length; i++) {
                    var item = tableData[i];
                    if (item["ReferenceInvitationCode"] == code) {
                        itemData = item;
                        break;
                    }
                }
                if (itemData == null) {
                    isVerified = false;
                    $("#lb-UpdateUserReferenceDlg-Reference").text("");
                    layer.msg(addStyle("验证失败: 无效的推荐人邀请码！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                    );
                } else {
                    isVerified = true;
                    layer.msg(addStyle("验证成功！"),
                        { icon: 1, time: 1 * 1000, offset: ["25%"], closeBtn: true }
                    );
                    $("#lb-UpdateUserReferenceDlg-Reference").text(itemData["ReferenceName"]);
                }
            }

            var isVerified = true;
            function onUpdateUserReferenceDlgOKBtnClick() {
                if (isVerified == true) {
                    layer.confirm("确定要修改推荐人吗？",
                        { icon: 3, title: "满堂创品", offset: "20%" },
                        function () {
                            var jsonData = {
                                UserId: userId,
                                ReferenceInvitationCode: $("#txt-UpdateUserReferenceDlg-ReferenceInvitationCode").val()
                            };
                            //console.log(jsonData);

                            var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                            $.ajax("/User/UpdateUserReferenceInvitationCode", {
                                method: "POST",
                                data: jsonData,
                                complete: function (jqXHR, textStatus) {
                                    layer.close(loadingIndex);
                                },
                                success: function (data, textStatus, jqXHR) {
                                    if (data.Success == true) {
                                        layer.close(layerId);
                                        layer.msg(addStyle("修改推荐人成功！"), {
                                            icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                                reloadTable();
                                            }
                                        });
                                    } else {
                                        layer.msg(addStyle("修改推荐人失败: " + data.Msg),
                                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                        );
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    layer.msg(addStyle("系统错误，请联系管理员！"),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                                }
                            });
                        }
                    );
                } else {
                    layer.msg(addStyle("请先输入正确的推荐人邀请码！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                    );
                }
            }
        }

        function onUpdateUserStateHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var userId = data["Id"];
            var state = data["State"];
            var name = data["Name"];
            //console.log(data);

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                resize: false,
                content: '<div Id="UpdateUserStateDlg2">' + $("#UpdateUserStateDlg").html() + '</div>'
            });

            $("#sel-UpdateUserStateDlg-State").val(state);
            $("#lb-UpdateUserStateDlg-Name").text(name);
            form.render("select");
            $("#btn-UpdateUserStateDlg-OK").click(onUpdateUserStateDlgOKBtnClick);

            function onUpdateUserStateDlgOKBtnClick() {
                layer.confirm("确定要更改会员状态吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/User/UpdateUserState", {
                            method: "POST",
                            data: {
                                UserId: userId,
                                State: $("#sel-UpdateUserStateDlg-State").val()
                            },
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(layerId);
                                    layer.msg(addStyle("更改会员状态成功！"), {
                                        icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                            reloadTable();
                                        }
                                    });
                                } else {
                                    layer.msg(addStyle("更改会员状态失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                    );
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );
            }
        }

        function onViewShopManagerLevelHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var userId = data["Id"];
            var shopManagerLevel = data["ShopManagerLevel"];
            //alert(shopManagerLevel);

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                resize: false,
                content: '<div Id="ViewShopManagerLevelDlg2">' + $("#ViewShopManagerLevelDlg").html() + '</div>',
                success: function (layero, index, that) {

                }
            });

            $("#btnViewShopManagerLevelOK").click(onViewShopManagerLevelOKBtnClick);
            $("#selShopManagerLevel").val(shopManagerLevel);
            form.render("select");

            function onViewShopManagerLevelOKBtnClick() {
                var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                    { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                $.ajax("/User/UpdateShopManagerLevelPercent", {
                    method: "POST",
                    data: {
                        UserId: userId,
                        Percent: $("#selShopManagerLevel").val()
                    },
                    complete: function (jqXHR, textStatus) {
                        layer.close(loadingIndex);
                    },
                    success: function (data, textStatus, jqXHR) {
                        if (data.Success == true) {
                            layer.msg(addStyle("更新成功！"), {
                                icon: 1, time: 1 * 1000, offset: ["25%"], closeBtn: true,
                                end: function () {
                                    layer.close(layerId);
                                    reloadTable();
                                }
                            });
                        } else {
                            layer.msg(addStyle("更新失败: " + data.Msg),
                                { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                            );
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg(addStyle("系统错误，请联系管理员！"),
                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                    }
                });
            }
        }

        function onResetPwdHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var _userId = data.Id;

            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                resize: false,
                content: '<div id="ResetPwdDlg2">' + $("#ResetPwdDlg").html() + '</div>'
            });

            $("#txt-resetPwdDlg-newPwd").val("");
            $("#txt-resetPwdDlg-newPwd2").val("");

            form.verify({
                pwd: [/\w{6,20}/, "密码格式不正确！"],
                pwd2: function (value, elem) {
                    if ($("#txt-resetPwdDlg-newPwd").val() != $("#txt-resetPwdDlg-newPwd2").val()) {
                        return "两次新密码输入不一致！"
                    }
                    return;
                }
            });

            form.on("submit(filter-resetPwdDlg-ok)", function (data) {
                //console.log(data);

                layer.confirm("确定要重设密码吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            NewPwd: hex_md5($("#txt-resetPwdDlg-newPwd").val()).toUpperCase(),
                            UserId: _userId
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/User/ResetPwd", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(_layerId);
                                    layer.msg(addStyle("重设密码成功！"), {
                                        icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                            reloadTable();
                                        }
                                    });
                                } else {
                                    layer.msg(addStyle("重设密码失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                    );
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );

                return false;
            });
        }

        function addStyle(str) {
            return '<span style="font-size: 16px;">' + str + '</span>';
        }
    });

})();